<?php

namespace App\Domain\Auth\Controllers;

use App\Domain\Auth\Requests\AuthPost;
use App\Domain\Auth\Services\AuthService;
use App\Events\OperationLog;
use App\Http\Controllers\Controller;
use App\Supports\Constant\OperationLogConst;
use App\Supports\Constant\ServiceConst;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class AuthController extends Controller
{
    /**
     * 登录获取token
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(AuthPost $request)
    {
        $request->validated();
        $params = [
            'account' => $request->input('account'),
            'password' => $request->input('password'),
        ];

        $data = (new AuthService())->Login($params);
        return $this->success([
            'token' => 'Bearer ' . $data['token'],
            "name" => $data["name"],
            "role_id" => $data['role_id']
        ]);

    }

    /**
     * 修改密码
     * @param Request $request
     * @return mixed
     */
    public function modifyPassword(Request $request)
    {
        $this->validate($request, [
            'oldPassword' => 'required|min:8|max:16',
            'newPassword' => 'required|min:8|max:16|different:oldPassword'
        ], [
            'oldPassword.required' => '密码必填',
            'oldPassword.min' => '密码最少8位',
            'oldPassword.max' => '密码最多16位',
            'newPassword.required' => '密码必填',
            'newPassword.min' => '密码最少8位',
            'newPassword.max' => '密码最多16位',
            'newPassword.different' => '新密码和旧密码不能相同',
        ]);

        $params = [
            'old_password' => $request->input('oldPassword'),
            'new_password' => $request->input('newPassword'),
        ];
        app(ServiceConst::SYSTEM_MANAGER)->createAuthDriver()->modifyPassword($params);
        return $this->success();
    }
    /**
     * 退出登录
     * @return mixed
     */
    public function logout()
    {
        auth('api')->logout();
        return $this->success([], '退出成功');
    }

    /**
     * 刷新token
     * @return mixed
     */
    public function refresh()
    {
        return $this->success([
            'access_token' => auth('api')->refresh(),
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ], '刷新成功');
    }


}
